package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.common.RoleEnum;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.entity.UserAddress;
import com.sqx.modules.health.service.IUserAddressService;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.vo.UserAddressVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户联系地址	 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-04-08
 */

@Api(value = "用户联系地址", tags = "用户联系地址", description = "")
@RestController
@RequestMapping("/health/userAddress")
public class UserAddressController {
    @Autowired
    private IUserAddressService userAddressService;

    @Autowired
    private IUserService userService;

    // 新增或更新
    @PostMapping("/websave")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户地址信息的id", paramType = "Integer"),
            @ApiImplicitParam(name = "uid",value = "用户地址信息对应的用户id", paramType = "Integer"),
            @ApiImplicitParam(name = "username",value = "用户地址信息对应的用户名称", paramType = "String"),
            @ApiImplicitParam(name = "phone",value = "用户地址信息对应的用户电话", paramType = "String"),
            @ApiImplicitParam(name = "address",value = "用户地址信息对应的用户地址", paramType = "String"),
            @ApiImplicitParam(name = "isDefault",value = "用户地址信息是否为用户的默认地址(默认为0: 不是默认地址)", paramType = "String"),
    })
    @ApiOperation(value = "新增或更新用户联系地址	", notes = "新增或更新用户联系地址	")
    public Result websave(@RequestBody UserAddress userAddress){
        // 如果没有默认地址就默认为0
        userAddress.setIsDefault(ObjectUtil.isEmpty(userAddress.getIsDefault()) ? "0" : userAddress.getIsDefault());
        if (ObjectUtil.isEmpty(userAddress.getId()) || ObjectUtil.equals(userAddress.getId(), 0)){
            // 新增操作
            if ("1".equals(userAddress.getIsDefault())){// 添加的默认地址
                // 首先判断该用户是否存在默认地址
                UserAddress defaultAddress = userAddressService.getDefaultAddress(userAddress.getUid());
                if (defaultAddress != null){ // 该用户已经有默认地址
                    return Result.error(Constants.CODE_500,"该用户已存在默认地址,操作失败!!");
                }
            }
        } else {// 修改操作
            // 首先判断该用户是否存在默认地址
            UserAddress defaultAddress = userAddressService.getDefaultAddress(userAddress.getUid());
            if (ObjectUtil.equals(userAddress.getIsDefault(), "1")){
                if (ObjectUtil.isNotEmpty(defaultAddress) && !ObjectUtil.equals(defaultAddress.getId(), userAddress.getId())){
                    // 如果存在默认地址 并且当前修改的不是默认地址数据 则不可以修改
                    return Result.error(Constants.CODE_500,"修改失败,该用户已存在默认地址!!");
                }
            }
        }
        return Result.success(userAddressService.saveOrUpdate(userAddress));
    }

    // 新增或更新
    @PostMapping("/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户地址信息的id", paramType = "Integer"),
            @ApiImplicitParam(name = "uid",value = "用户地址信息对应的用户id", paramType = "Integer"),
            @ApiImplicitParam(name = "username",value = "用户地址信息对应的用户名称", paramType = "String"),
            @ApiImplicitParam(name = "phone",value = "用户地址信息对应的用户电话", paramType = "String"),
            @ApiImplicitParam(name = "address",value = "用户地址信息对应的用户地址", paramType = "String"),
            @ApiImplicitParam(name = "isDefault",value = "用户地址信息是否为用户的默认地址(默认为0: 不是默认地址)", paramType = "String"),
    })
    @ApiOperation(value = "新增或更新用户联系地址	", notes = "新增或更新用户联系地址	")
    public Result save(@RequestBody UserAddress userAddress){
        // 如果没有默认地址就默认为0
        userAddress.setIsDefault(ObjectUtil.isEmpty(userAddress.getIsDefault()) ? "0" : userAddress.getIsDefault());
        return Result.success(userAddressService.saveOrUpdate(userAddress));
    }


    // 根据ID删除
    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除用户联系地址	", notes = "根据ID删除用户联系地址	")
    public Result delete(@PathVariable Integer id){
        return Result.success(userAddressService.removeById(id));
    }

    // 根据IDS删除
    @GetMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除用户联系地址	", notes = "根据IDS删除用户联系地址	")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(userAddressService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部用户联系地址	", notes = "查询全部用户联系地址	")
    public Result findAll(){
        return Result.success(userAddressService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录用户联系地址", notes = "根据ID查询一条记录用户联系地址")
    public Result findOne(@RequestParam Integer id){
        return Result.success(userAddressService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询用户联系地址	", notes = "分页查询用户联系地址	")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam Long loginId, // 当前登录人的id
                           @RequestParam(required = false, defaultValue = "") Long uid){
//        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
//        // 查询当前用户是否为普通用户角色
//        if (getUser(loginId)){
//            // 当前登录人为普通用户角色  只能查看自己的地址信息
//            queryWrapper.eq("uid",loginId);
//        }
//        if (ObjectUtil.isNotEmpty(uid)){
//            queryWrapper.eq("uid",uid);
//        }
//        queryWrapper.orderByDesc("id");
//        Page<UserAddress> page = userAddressService.page(new Page<>(pageNum, pageSize), queryWrapper);
//        // 将查询到数据copy到一个新的集合中
//        List<UserAddressVo> userAddressVos = MyBeanUtil.collectionCopy(page.getRecords(), UserAddressVo.class);
        Page<UserAddressVo> result = new Page<>();
//        result.setRecords(userAddressVos);
//        // 将查询到的数据赋值到返回数据中
//        result.setTotal(page.getTotal());
//        for (UserAddressVo record : result.getRecords()) {
//            if (ObjectUtil.isNotEmpty(record.getUid())){
//                User user = userService.getById(record.getUid());
//                record.setUname(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
//            }
//        }
        return  Result.success(result);
    }

    @ApiOperation(value = "根据用户id获取用户下所有的地址信息")
    @ApiImplicitParam(name = "uid",value = "当前登录用户的id",paramType = "Integer")
    @GetMapping("/getAddress")
    public Result getAddressByUserId(@RequestParam Long uid){
        return Result.success(userAddressService.getAddressByUserId(uid));
    }

    @ApiOperation(value = "根据用户id获取用户默认地址")
    @ApiImplicitParam(name = "uid",value = "当前登录用户的id",paramType = "Integer")
    @GetMapping("/getDefaultAddress")
    public Result getDefaultAddressByUserId(@RequestParam Long uid){
        // 查询当前用户是否存在默认地址
        UserAddress defaultAddress = userAddressService.getDefaultAddress(uid);
        if (ObjectUtil.isNotEmpty(defaultAddress)){
            // 如果存在  直接返回默认地址
            return Result.success(defaultAddress);
        } else {
            // 如果不存在 则返回所有地址中的任意一个
            List<UserAddress> addressByUserId = userAddressService.getAddressByUserId(uid);
            if (ObjectUtil.isEmpty(addressByUserId)){
                return Result.error(Constants.CODE_500,"无地址信息");
            }
            return Result.success(addressByUserId.get(0));
        }
    }

    @ApiOperation(value = "更改默认地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "要设为默认地址的地址ID",paramType = "Integer"),
            @ApiImplicitParam(name = "uid",value = "当前登录用户的id",paramType = "Integer"),
    })
    @GetMapping("/setDefault")
    public Result setDefaultAddress(Long id,Long uid){

        // 查询当前用户下是否存在默认地址
        UserAddress address = userAddressService.getDefaultAddress(uid);

        // 如果用户存在默认地址 并且设置默认地址的id和当前默认地址id一致 就认为用户要取消默认地址
        if (ObjectUtil.isNotEmpty(address) && ObjectUtil.equals(address.getId(), id)){
            userAddressService.setDefaultAddress(address.getId(),0);
            return Result.success();
        }

        // 如果存在 -> 就先将查询到的地址设置为非默认地址 然后再设置当前地址为默认地址
        if (ObjectUtil.isNotEmpty(address)){
            // 将查询到的地址设置为非默认地址
            userAddressService.setDefaultAddress(address.getId(),0);
        }

        // 如果没有默认地址则直接将地址设置为默认地址
        Integer line = userAddressService.setDefaultAddress(id,1);

        if (line > 0) {
            return Result.success();
        } else {
            return Result.error();
        }

    }


    /**
     * 判断当前用户是不是普通用户
     * @param loginId
     * @return
     */
    private boolean getUser(Long loginId){
        SysUserEntity user = userService.findRole(loginId, RoleEnum.ROLE_USER);
        if (ObjectUtil.isNotEmpty(user)){
            return true;
        } else {
            return false;
        }
    }

}

